// pages/companyDetails/companyDetails.js
//获取应用实例  
var app = getApp()
Page({
  data: {
    company_id: null,
    reward_id: null,
    predict_id: null,


    companyInfo: null,
    /**
     * payDialog
     */
    passWord: '',
    //passWord1: '',
    passWordArr: [],

    formValue: null,
    /**
     * tips
     */
    tipsInfo: {
      tipsType: null,
      showTopTips: false,
      errorMsg: null,
    },


    valid_score: 0,

    inputText: 100,
    /**
     * Dialog
     */

    showAuthorityDialog: false,

    showPayDialog: false,
    showPwdErrorDialog: false,
    showPaySuccessDialog: false,
    showInsufficientDialog: false,
    /** 
      * 页面配置 
      */
    winWidth: 0,
    winHeight: 0,
    // tab切换  
    currentTab: 0,
    fixed: false,
  },
  onLoad: function (options) {
    var that = this;

    // 若从log进入
    if (options.predict_id) {
      that.setData({
        predict_id: options.predict_id,
        currentTab: 1,
        fixed: true,
      });


      // 获取predict具体信息
      wx.request({
        url: app.globalData.server + '/predict/predict/?predict_id=' + that.data.predict_id,
        method: 'GET',
        data: {},
        header: {
          'content-type': 'application/x-www-form-urlencoded', // 默认值
          'Authorization': 'Bearer ' + app.globalData.token,
          'x-wxapp-signature': null,
          'x-wxapp-timestamp': app.getTimestamp(),
          'x-wxapp-nonce': app.getRandom()
        },
        success: function (res) {
          console.log(res);
          that.setData({
            formValue: res.data.data,
            inputText: res.data.data.principle,
          });
        }
      })




      // 从company_panel进入
    } else {
      that.setData({
        company_id: options.company_id,
      })


      //console.log(that.data.company_id);

      // 获取可用点数
      if (app.globalData.userType == 2) {
        that.setData({
          valid_score: app.globalData.userInfo.valid_score,
        })
      }
      /**
       * 获取企业信息
       */
      wx.request({
        url: app.globalData.server + '/user/company/?id=' + that.data.company_id,
        method: 'GET',
        data: {},
        header: {
          'content-type': 'application/x-www-form-urlencoded', // 默认值
          'Authorization': 'Bearer ' + app.globalData.token,
          'x-wxapp-signature': null,
          'x-wxapp-timestamp': app.getTimestamp(),
          'x-wxapp-nonce': app.getRandom()
        },
        success: function (res) {
          that.setData({
            companyInfo: res.data.data,
          });

          /**
           * 获取reward_id
           */

          if (that.data.companyInfo.reward_available) {

            wx.request({
              url: app.globalData.server + '/predict/reward/?user_id=' + that.data.company_id,
              method: 'GET',
              data: {},
              header: {
                'content-type': 'application/x-www-form-urlencoded', // 默认值
                'Authorization': 'Bearer ' + app.globalData.token,
                'x-wxapp-signature': null,
                'x-wxapp-timestamp': app.getTimestamp(),
                'x-wxapp-nonce': app.getRandom()
              },
              success: function (res) {
                var list = res.data.data;
                if (list.length != 0) {
                  var id = list[0].id;
                  that.setData({
                    reward_id: id,
                  });
                }
              }
            })
          }
        }
      })
    }
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },

  /**
   * 确定发布按钮
   */
  getFormValues: function (e) {
    var that = this;
    console.log(e.detail);
    var that = this;
    // 检查各项的值以及错误提示
    if (e.detail.value.net_profit == "" && e.detail.value.market_price == "") {
      that.showTopTips('请填写完整', 'warn');
      that.setData({
        formValue: null,
      });
      return;

    } else {
      that.setData({
        formValue: e.detail.value,
      })
    }
    /**
     * 提交一个全新的预测点评
     */
    var predict_market_price = false;
    var predict_net_profit = false;

    var market_price = that.data.formValue.market_price;
    var net_profit = that.data.formValue.net_profit;

    if (market_price != "") {
      predict_market_price = true;
    } else {
      market_price = 0;
    }
    if (net_profit != "") {
      predict_net_profit = true;
    } else {
      net_profit = 0;
    }

    console.log("market_price:" + market_price);

    console.log("net_profit:" + net_profit);


    if (that.data.predict_id == null) {
      wx.request({
        url: app.globalData.server + '/predict/predict/',
        method: 'POST',
        data: {
          'reward_id': that.data.reward_id,
          'principal': that.data.formValue.principal,
          'market_price': market_price,
          'net_profit': net_profit,
          'predict_market_price': predict_market_price,
          'predict_net_profit': predict_net_profit,
          'comment': that.data.formValue.comment,
          //id:
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded', // 默认值
          'Authorization': 'Bearer ' + app.globalData.token,
          'x-wxapp-signature': null,
          'x-wxapp-timestamp': app.getTimestamp(),
          'x-wxapp-nonce': app.getRandom()
        },
        success: function (res) {
          console.log(res);

          // 进入支付
          if (res.data.message == 'ok') {
            //that.pay();
            that.setData({
              predict_id: res.data.data.predict_id,
            })
            that.showPayDialog();
          } else if (res.data.message == 'Insufficient valid score') {
            that.showTopTips('可用积分不足，请充值', 'warn');
          }
        },
      })
    } else {
      /**
       * 支付未支付的点评预测
       */
      that.showPayDialog();
    }
  },


  /** 
    * 点数调整器  
    */
  plus: function () {
    /*
    if (this.data.inputText == this.data.valid_score) {
      return;
    }
    */

    if (this.data.fixed) {
      return;
    }
    var newInputText = this.data.inputText + 100;
    this.setData({
      inputText: newInputText
    })
  },
  minus: function () {
    if (this.data.fixed) {
      return;
    }
    if (this.data.inputText == 100) {
      return;
    }
    var newInputText = this.data.inputText - 100;
    this.setData({
      inputText: newInputText
    })
  },
  /**
   * tips提示 
   */
  showTopTips: function (msg, Type) {
    var that = this;

    that.setData({
      'tipsInfo.showTopTips': true,
      'tipsInfo.errorMsg': msg,
      'tipsInfo.tipsType': Type
    });
    setTimeout(function () {
      that.setData({
        'tipsInfo.showTopTips': false
      });
    }, 3000);
  },
  /** 
    * 滑动切换tab 
    */
  bindChange: function (e) {
    var that = this;
    // 锁定
    if (that.data.fixed) {
      that.setData({ currentTab: 1 });
      return;
    }

    // 指向发起预测点评页面
    if (e.detail.current == 1) {
      var hasAuthority = app.checkAccessAuthority(1);
      //console.log(hasAuthority);
      if (!hasAuthority) {
        // 显示用户无权限的弹窗
        that.showAuthorityDialog();
      } else {
        app.editTabBar();
      }
    }

    that.setData({ currentTab: e.detail.current });

  },
  /** 
   * 点击tab切换 
   */
  swichNav: function (e) {
    var that = this;

    // 锁定
    if (that.data.fixed) {
      return;
    }

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      // 指向发起预测点评页面
      if (e.target.dataset.current == 1) {
        var hasAuthority = app.checkAccessAuthority(1);
        //console.log(hasAuthority);
        if (!hasAuthority) {
          // 显示用户无权限的弹窗
          that.showAuthorityDialog();

        } else {
          app.editTabBar();
        }
      }

      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  /** 
   * PayDialog相关
   */
  showPayDialog: function (e) {
    let that = this;
    that.setData({
      showPayDialog: true,
      fixed: true,
    });
  },
  hidePayDialog: function () {
    var that=this;
    if (that.data.predict_id == null) {
      this.setData({
        
        fixed: false,
      });
    }


    this.setData({
      showPayDialog: !this.data.showPayDialog,
      passWord: '', 
      //passWord1: '',
      passWordArr: [],
      //fixed: false,
    });
  },
  /**
   * PwdErrorDialog相关
   */
  showPwdErrorDialog: function () {
    var that = this;
    that.setData({
      showPwdErrorDialog: true,
      fixed: true,
    })
  },
  hidePwdErrorDialog: function () {
    var that = this;
    that.setData({
      showPwdErrorDialog: !this.data.showPwdErrorDialog,
      passWord: '',
      //passWord1: '',
      passWordArr: [],
    });
  },
  giveUpPay: function () {
    var that = this;
    that.hidePwdErrorDialog();
    that.hidePayDialog();
    wx.reLaunch({
      url: '../init/init',
    })
  },
  /**
   * PaySuccessDialog
   */
  showPaySuccessDialog: function () {
    var that = this;
    that.setData({
      showPaySuccessDialog: true,
      fixed: true,
    })
  },
  hidePaySuccessDialog: function () {
    var that = this;
    this.setData({
      showPaySuccessDialog: false,
      fixed: false,
    });
    wx.reLaunch({
      url: '../init/init',
    })
  },
  /**
   * InsufficientDialog
   */
  showInsufficientDialog: function () {
    var that = this;
    that.setData({
      showInsufficientDialog: true,
      fixed: true,
    })
  },
  hideInsufficientDialog: function () {
    var that = this;
    this.setData({
      showInsufficientDialog: false,
      fixed: false,
    });
    wx.redirectTo({
      url: '../userCenter/uuserCenter',
    })
  },

  /**
   * AuthorityDialog相关
   */
  showAuthorityDialog: function () {
    this.setData({
      showAuthorityDialog: true,
    })
  },
  hideAuthorityDialog: function () {
    this.setData({
      showAuthorityDialog: !this.data.showAuthorityDialog,
      currentTab: 0,
    });
    wx.reLaunch({
      url: '../index/index',
    });
  },
  /** 
   * 支付相关 
   */
  onChangeInput: function (e) {
    let that = this;
    var pwdArr = that.data.passWordArr;

    if (e.detail.value.length > that.data.passWord.length) {

      pwdArr.push(true);
    } else if (e.detail.value.length < that.data.passWord.length) {
      pwdArr.pop();
    }
    that.setData({
      passWordArr: pwdArr,
      passWord: e.detail.value,
      //passWord1:'',
    })
    // 密码输入完成
    console.log(e.detail.value);
    if (e.detail.value.length == 6) {
      that.pay();
    }
  },
  reInput:function(){
    var that=this;
    that.setData({
      showPayDialog:true,
    })
  },
  pay: function () {
    var that = this;

    wx.request({
      url: app.globalData.server + '/predict/predict/?predict_id=' + that.data.predict_id + '&passwd=' + that.data.passWord,
      method: 'PUT',
      data: {
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded', // 默认值
        'Authorization': 'Bearer ' + app.globalData.token,
        'x-wxapp-signature': null,
        'x-wxapp-timestamp': app.getTimestamp(),
        'x-wxapp-nonce': app.getRandom()
      },
      success: function (res) {
        console.log(res);
        if (res.data.message == "passwd wrong") {
          that.showPwdErrorDialog();
        } else if (res.data.message == "ok") {
          that.showPaySuccessDialog();
        } else if (res.data.message == "Insufficient valid score") {
          that.showInsufficientDialog();
        }

      }
    })
  },


})  